<template>
  <div class="dashboard">
    <!-- 头部信息栏 -->
    <header class="app-header">
      <div class="header-left">
        <h1 class="app-title">工作时间记录系统</h1>
        <div class="trip-info">
          <span v-if="store.user.tripStartDate" class="trip-start">
            出差开始: {{ formatDate(store.user.tripStartDate) }}
          </span>
          <span v-else class="no-trip">尚未设置出差开始日期</span>
        </div>
      </div>
      <div class="header-right">
        <el-button @click="handleLogout" type="danger">退出登录</el-button>
      </div>
    </header>

    <!-- 主体内容区域 -->
    <main class="app-main">
      <!-- 左侧日历区域 -->
      <section class="calendar-section">
        <div class="calendar-header">
          <el-button @click="prevMonth" :icon="ArrowLeft"></el-button>
          <h2 class="month-title">{{ currentYear }}年{{ currentMonth }}月</h2>
          <el-button @click="nextMonth" :icon="ArrowRight"></el-button>
          <el-button @click="goToday" type="primary" plain>回到今天</el-button>
        </div>

        <div class="calendar-container">
          <!-- 周几标题行 -->
          <div class="weekday-header">
            <div 
              v-for="weekday in weekdays" 
              :key="weekday"
              class="weekday-cell"
            >
              {{ weekday }}
            </div>
          </div>

          <!-- 日期网格 -->
          <div class="calendar-grid">
            <div 
              v-for="(day, index) in calendarDays" 
              :key="day.date || `empty-${index}`"
              :class="getDayClasses(day)"
              @click="onDayClick(day)"
            >
              <!-- 空白日期 -->
              <template v-if="day.isEmpty">
                <!-- 空白格子 -->
              </template>
              
              <!-- 正常日期 -->
              <template v-else>
                <!-- 日期数字 -->
                <div class="day-number">{{ day.day }}</div>
                
                <!-- 日期类型标签 -->
                <div class="day-labels">
                  <span class="type-label">{{ day.dateTypeName }}</span>
                </div>
                
                <!-- 节假日名称 -->
                <div v-if="day.holidayName" class="holiday-name">
                  {{ day.holidayName }}
                </div>
                
                <!-- 用户状态标记 -->
                <div v-if="day.userStatus" class="user-status">
                  <el-tag :type="getStatusTagType(day.userStatus)" size="small">
                    {{ getUserStatusText(day.userStatus) }}
                  </el-tag>
                </div>
                
                <!-- 今天标记 -->
                <div v-if="day.isToday" class="today-marker"></div>
              </template>
            </div>
          </div>
        </div>
      </section>

      <!-- 右侧信息面板 -->
      <aside class="info-panel">
        <!-- 统计信息卡片 -->
        <el-card class="stats-card">
          <template #header>
            <div class="card-header">
              <div class="header-left">
                <div class="title-row">
                  <span class="header-title">统计概览</span>
                  <el-checkbox v-model="includeTravel" @change="updateStatistics" size="small" class="travel-checkbox">
                    <span>车程计入休息</span>
                    <el-tooltip content="休息期间的第一天和最后一天默认为车程时间，勾选后将这些天数计入休息天数" placement="top">
                      <el-icon style="margin-left: 4px; color: #909399; font-size: 12px;"><InfoFilled /></el-icon>
                    </el-tooltip>
                  </el-checkbox>
                </div>
                <div class="date-range-selector">
                  <el-date-picker
                    v-model="statisticsDateRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    size="small"
                    :disabled-date="disableStatisticsDate"
                    @change="onStatisticsDateRangeChange"
                    :clearable="true"
                    style="width: 260px;"
                  />
                  <el-button 
                    size="small" 
                    type="primary" 
                    link 
                    @click="resetStatisticsDateRange"
                    style="margin-left: 8px;"
                  >
                    重置
                  </el-button>
                </div>
              </div>
            </div>
          </template>
          
          <div class="stats-content">
            <div class="stat-item">
              <span class="stat-label">工作天数:</span>
              <span class="stat-value work-days">{{ store.statistics.workDays }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">休息天数:</span>
              <span class="stat-value rest-days">{{ store.statistics.restDays }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">应休天数:</span>
              <span class="stat-value should-rest">{{ store.statistics.shouldRestDays }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">欠休天数:</span>
              <span class="stat-value owed-rest" :class="{ 'negative': store.statistics.owedRestDays < 0 }">
                {{ store.statistics.owedRestDays }}
              </span>
            </div>
          </div>
        </el-card>

        <!-- 休息记录列表 -->
        <el-card class="records-card">
          <template #header>
            <span>休息记录</span>
          </template>
          
          <div class="records-content">
            <div 
              v-for="record in store.restRecords" 
              :key="record.id"
              class="record-item"
            >
              <div class="record-dates">
                {{ formatDate(record.startDate) }} - 
                {{ record.endDate ? formatDate(record.endDate) : '进行中' }}
              </div>
              <div class="record-description">{{ record.description }}</div>
              <div class="record-actions">
                <el-button size="small" @click="editRecord(record)">编辑</el-button>
                <el-button size="small" type="danger" @click="deleteRecord(record)">删除</el-button>
              </div>
            </div>
            
            <el-empty v-if="store.restRecords.length === 0" description="暂无休息记录"></el-empty>
          </div>
        </el-card>
      </aside>
    </main>

    <!-- 日期操作对话框 -->
    <el-dialog v-model="showDayDialog" :title="dayDialogTitle" width="500px">
      <div class="day-info">
        <p class="selected-date">{{ selectedDay?.date }} ({{ selectedDay?.weekdayName }})</p>
        <p class="date-type">{{ selectedDay?.dateTypeName }}</p>
        <p v-if="selectedDay?.holidayName" class="holiday-info">{{ selectedDay?.holidayName }}</p>
      </div>
      
      <div class="day-actions">
        <!-- 情况1：没有出差开始日期 -->
        <template v-if="!store.user.tripStartDate">
          <el-button 
            @click="setTripStart"
            type="primary"
            size="large"
            style="width: 100%"
          >
            设为出差开始日期
          </el-button>
          <p class="action-tip">选择此日期作为您的出差开始日期</p>
        </template>
        
        <!-- 情况2：已有出差开始日期，选择的日期早于出差开始日期 -->
        <template v-else-if="selectedDay && selectedDay.isBeforeTrip">
          <el-button 
            @click="changeTripStart"
            type="warning"
            size="large"
            style="width: 100%"
          >
            修改出差开始日期为此日期
          </el-button>
          <p class="action-tip">当前出差开始日期：{{ formatDate(store.user.tripStartDate) }}</p>
        </template>
        
        <!-- 情况3：复杂休息场景处理 -->
        <template v-else-if="selectedDay && availableOptions.length > 0">
          <div class="complex-options">
            <p class="options-title">请选择操作：</p>
            
            <!-- 高优先级操作 -->
            <div 
              v-for="(option, index) in highPriorityOptions" 
              :key="`high-${index}`"
              class="option-item high-priority"
            >
              <el-button 
                @click="handleComplexAction(option)"
                :type="getOptionButtonType(option.type, option.priority)"
                size="large"
                style="width: 100%; margin-bottom: 8px;"
              >
                {{ option.label }}
              </el-button>
              <p class="option-description">{{ option.description }}</p>
            </div>
            
            <!-- 低优先级操作（折叠显示） -->
            <div v-if="lowPriorityOptions.length > 0" class="low-priority-section">
              <el-button 
                @click="showLowPriorityOptions = !showLowPriorityOptions"
                type="info"
                size="small"
                text
                style="width: 100%; margin: 8px 0;"
              >
                <span>{{ showLowPriorityOptions ? '收起' : '更多选项' }}</span>
                <el-icon style="margin-left: 4px;">
                  <ArrowDown v-if="!showLowPriorityOptions" />
                  <ArrowUp v-else />
                </el-icon>
              </el-button>
              
              <div v-show="showLowPriorityOptions" class="low-priority-options">
                <div 
                  v-for="(option, index) in lowPriorityOptions" 
                  :key="`low-${index}`"
                  class="option-item low-priority"
                >
                  <el-button 
                    @click="handleComplexAction(option)"
                    :type="getOptionButtonType(option.type, option.priority)"
                    size="default"
                    plain
                    style="width: 100%; margin-bottom: 6px;"
                  >
                    {{ option.label }}
                  </el-button>
                  <p class="option-description low">{{ option.description }}</p>
                </div>
              </div>
            </div>
          </div>
        </template>
        
        <!-- 情况4：无可用操作 -->
        <template v-else>
          <div class="no-options">
            <el-icon size="48" color="#c0c4cc"><InfoFilled /></el-icon>
            <p>此日期暂无可用操作</p>
            <p class="no-options-tip">
              <span v-if="isFutureDateLimited">已有未来日期选择，不能再选择其他未来日期</span>
              <span v-else>请选择其他日期</span>
            </p>
          </div>
        </template>
      </div>
    </el-dialog>

    <!-- 休息记录编辑对话框 -->
    <RestRecordDialog 
      v-model="showRestDialog"
      :record="editingRecord"
      :selected-date="selectedDay?.date"
      :preset-start-date="selectedRestStartDate"
      :preset-end-date="selectedRestEndDate"
      :date-range="selectedDateRange"
      @save="saveRestRecord"
    />
    
    <!-- 简化日期选择器 -->
    <SimpleDatePicker
      v-model="showSimpleDatePicker"
      :title="simpleDatePickerConfig.title"
      :info-text="simpleDatePickerConfig.infoText"
      :placeholder="simpleDatePickerConfig.placeholder"
      :date-range="simpleDatePickerConfig.dateRange"
      :reference-date="simpleDatePickerConfig.referenceDate"
      @confirm="handleSimpleDateConfirm"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, ArrowRight, InfoFilled, ArrowDown, ArrowUp } from '@element-plus/icons-vue'
import { useAppStore } from '../stores/index.js'
import RestRecordDialog from '../components/RestRecordDialog.vue'
import SimpleDatePicker from '../components/SimpleDatePicker.vue'

const router = useRouter()
const store = useAppStore()

// 响应式数据
const currentYear = ref(new Date().getFullYear())
const currentMonth = ref(new Date().getMonth() + 1)
const calendarDays = ref([])
const includeTravel = ref(false)
const statisticsDateRange = ref(null)
const showDayDialog = ref(false)
const showRestDialog = ref(false)
const selectedDay = ref(null)
const editingRecord = ref(null)
const selectedRestStartDate = ref(null)
const selectedRestEndDate = ref(null)
const selectedDateRange = ref(null)
const showLowPriorityOptions = ref(false)
const showSimpleDatePicker = ref(false)
const simpleDatePickerConfig = ref({})

const weekdays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']

const dayDialogTitle = computed(() => {
  if (!selectedDay.value) return ''
  return `${selectedDay.value.date} (${selectedDay.value.weekdayName})`
})

// 可用操作选项
const availableOptions = computed(() => {
  if (!selectedDay.value || !store.user.tripStartDate || selectedDay.value.isBeforeTrip) {
    return []
  }
  return store.analyzeClickOptions(selectedDay.value.date)
})

// 是否受未来日期限制
const isFutureDateLimited = computed(() => {
  if (!selectedDay.value) return false
  const today = new Date().toISOString().split('T')[0]
  const isFuture = selectedDay.value.date > today
  return isFuture && store.futureSelectedDate && store.futureSelectedDate !== selectedDay.value.date
})

// 高优先级选项
const highPriorityOptions = computed(() => {
  return availableOptions.value.filter(option => option.priority === 'high')
})

// 低优先级选项
const lowPriorityOptions = computed(() => {
  return availableOptions.value.filter(option => option.priority === 'low')
})

onMounted(async () => {
  try {
    // 检查本地登录状态
    if (!store.checkLoginStatus()) {
      ElMessage.warning('请先登录')
      router.push('/login')
      return
    }
    
    // 验证 token 有效性
    const isValid = await store.validateToken()
    if (!isValid) {
      ElMessage.error('登录已过期，请重新登录')
      await store.logout()
      router.push('/login')
      return
    }
    
    // 先加载用户状态和节假日数据
    await Promise.all([
      store.getUserStatus(),
      store.getHolidayData(currentYear.value)
    ])
    
    // 如果用户已设置出差开始日期，初始化日期范围并加载统计数据
    if (store.user.tripStartDate) {
      initializeStatisticsDateRange()
      await store.getStatistics()
    }
    
    // 生成日历
    generateCalendar()
  } catch (error) {
    console.error('初始化失败:', error)
    ElMessage.error('数据加载失败')
  }
})

// 生成日历数据
const generateCalendar = () => {
  const year = currentYear.value
  const month = currentMonth.value
  const daysInMonth = new Date(year, month, 0).getDate()
  const firstDay = new Date(year, month - 1, 1)
  
  // 使用本地日期，避免时区问题
  const today = new Date()
  const todayStr = today.getFullYear() + '-' + 
                  String(today.getMonth() + 1).padStart(2, '0') + '-' + 
                  String(today.getDate()).padStart(2, '0')
  
  calendarDays.value = []
  
  // 计算第一天是周几（周一为1，周日为7）
  const firstWeekday = firstDay.getDay() === 0 ? 7 : firstDay.getDay()
  
  // 添加上个月的空白日期以对齐
  for (let i = 1; i < firstWeekday; i++) {
    calendarDays.value.push({
      date: null,
      day: null,
      isEmpty: true
    })
  }
  
  // 添加当月的日期
  for (let day = 1; day <= daysInMonth; day++) {
    const currentDate = new Date(year, month - 1, day)
    const dateStr = formatDate(currentDate)
    const monthDayKey = formatMonthDay(currentDate)
    
    const dayData = {
      date: dateStr,
      day: day,
      weekday: currentDate.getDay() === 0 ? 7 : currentDate.getDay(),
      weekdayName: getWeekdayName(currentDate),
      dateType: getDateType(currentDate, monthDayKey),
      dateTypeName: getDateTypeName(currentDate, monthDayKey),
      holidayName: getHolidayName(monthDayKey),
      isBeforeTrip: isBeforeTrip(dateStr),
      isToday: dateStr === todayStr,
      userStatus: getUserStatus(dateStr),
      isEmpty: false
    }
    
    calendarDays.value.push(dayData)
  }
}

// 工具函数
const formatDate = (date) => {
  if (typeof date === 'string') return date
  if (date instanceof Date) {
    // 使用本地日期，避免时区问题
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  }
  return date
}

const formatMonthDay = (date) => {
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${month}-${day}`
}

const getWeekdayName = (date) => {
  const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  return weekdays[date.getDay()]
}

const getDateType = (date, monthDayKey) => {
  const yearKey = date.getFullYear().toString()
  const holidayData = store.holidayData[yearKey] || {}
  
  // 检查节假日数据
  if (holidayData[monthDayKey]) {
    return holidayData[monthDayKey].isHoliday ? 2 : 3
  }
  
  // 检查周末
  const dayOfWeek = date.getDay()
  if (dayOfWeek === 0 || dayOfWeek === 6) {
    return 1
  }
  
  return 0 // 工作日
}

const getDateTypeName = (date, monthDayKey) => {
  const type = getDateType(date, monthDayKey)
  const typeNames = ['工作日', '周末', '节假日', '调休工作日']
  return typeNames[type]
}

const getHolidayName = (monthDayKey) => {
  const yearKey = currentYear.value.toString()
  const holidayData = store.holidayData[yearKey] || {}
  return holidayData[monthDayKey]?.name || null
}

const isBeforeTrip = (dateStr) => {
  if (!store.user.tripStartDate) return true
  return new Date(dateStr) < new Date(store.user.tripStartDate)
}

const isSameDay = (date1, date2) => {
  return formatDate(date1) === formatDate(date2)
}

const getUserStatus = (dateStr) => {
  if (dateStr === store.user.tripStartDate) return 'trip_start'
  
  // 使用本地日期，避免时区问题
  const today = new Date()
  const todayStr = today.getFullYear() + '-' + 
                  String(today.getMonth() + 1).padStart(2, '0') + '-' + 
                  String(today.getDate()).padStart(2, '0')
  
  // 检查是否在休息记录中
  for (const record of store.restRecords) {
    if (dateStr === record.startDate) return 'rest_start'
    if (dateStr === record.endDate) return 'rest_end'
    
    // 对于进行中的休息，只计算到今天
    const effectiveEndDate = record.endDate || (store.futureSelectedDate || todayStr)
    
    if (dateStr > record.startDate && dateStr <= effectiveEndDate) {
      return 'rest_period'
    }
  }
  
  return null
}

const getDayClasses = (day) => {
  if (day.isEmpty) {
    return ['calendar-day', 'empty-day']
  }
  
  return [
    'calendar-day',
    `date-type-${day.dateType}`,
    {
      'before-trip': day.isBeforeTrip,
      'trip-start': day.userStatus === 'trip_start',
      'rest-period': day.userStatus?.includes('rest'),
      'is-today': day.isToday
    }
  ]
}

const getStatusTagType = (status) => {
  const types = {
    'trip_start': 'success',
    'rest_start': 'warning',
    'rest_end': 'warning',
    'rest_period': 'info'
  }
  return types[status] || 'info'
}

const getUserStatusText = (status) => {
  const texts = {
    'trip_start': '出差开始',
    'rest_start': '休息开始',
    'rest_end': '休息结束',
    'rest_period': '休息中'
  }
  return texts[status] || ''
}

// 事件处理
const onDayClick = (day) => {
  if (day.isEmpty) return
  selectedDay.value = day
  showLowPriorityOptions.value = false // 重置低优先级选项显示状态
  showDayDialog.value = true
}

const setTripStart = async () => {
  try {
    await store.setTripStartDate(selectedDay.value.date)
    ElMessage.success('出差开始日期设置成功')
    showDayDialog.value = false
    
    // 设置出差开始日期后，初始化日期范围并加载统计数据
    initializeStatisticsDateRange()
    try {
      await store.getStatistics()
    } catch (error) {
      console.warn('加载统计数据失败:', error)
    }
    
    generateCalendar()
  } catch (error) {
    ElMessage.error('设置失败')
  }
}

const changeTripStart = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要将出差开始日期修改为 ${selectedDay.value.date} 吗？`, 
      '修改出差开始日期', 
      { type: 'warning' }
    )
    
    await store.setTripStartDate(selectedDay.value.date)
    ElMessage.success('出差开始日期修改成功')
    showDayDialog.value = false
    
    // 修改出差开始日期后，重新初始化日期范围并加载统计数据
    initializeStatisticsDateRange()
    try {
      await store.getStatistics()
    } catch (error) {
      console.warn('加载统计数据失败:', error)
    }
    
    generateCalendar()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('修改失败')
    }
  }
}

const startRest = async () => {
  try {
    const record = {
      startDate: selectedDay.value.date,
      endDate: null,
      description: `从${selectedDay.value.date}开始休息`
    }
    
    await store.addRestRecord(record)
    ElMessage.success('休息开始记录添加成功')
    showDayDialog.value = false
    generateCalendar()
  } catch (error) {
    ElMessage.error('添加失败')
  }
}

const endRest = async () => {
  try {
    // 找到最近的未结束休息记录
    const ongoingRest = store.restRecords.find(r => !r.endDate)
    if (!ongoingRest) {
      ElMessage.error('没有找到进行中的休息记录')
      return
    }
    
    await store.updateRestRecord(ongoingRest.id, {
      ...ongoingRest,
      endDate: selectedDay.value.date,
      description: ongoingRest.description + ` (结束于${selectedDay.value.date})`
    })
    
    ElMessage.success('休息结束记录更新成功')
    showDayDialog.value = false
    generateCalendar()
  } catch (error) {
    ElMessage.error('更新失败')
  }
}

// 获取下一步操作类型
const getNextAction = () => {
  if (!selectedDay.value || !store.user.tripStartDate) return null
  
  const selectedDate = selectedDay.value.date
  
  // 检查是否有进行中的休息记录
  const ongoingRest = store.restRecords.find(r => !r.endDate)
  if (ongoingRest) {
    return 'rest_end'
  }
  
  // 检查选择的日期是否在已有的休息记录中
  const isInRestPeriod = store.restRecords.some(r => {
    return selectedDate >= r.startDate && 
           (r.endDate ? selectedDate <= r.endDate : true)
  })
  
  if (isInRestPeriod) {
    return 'rest_end'
  }
  
  return 'rest_start'
}

// 获取操作提示
const getActionTip = () => {
  const action = getNextAction()
  
  if (action === 'rest_start') {
    return '点击开始休息，系统将记录您的休息开始日期'
  } else if (action === 'rest_end') {
    const ongoingRest = store.restRecords.find(r => !r.endDate)
    if (ongoingRest) {
      return `当前休息开始于：${ongoingRest.startDate}`
    }
    return '点击结束当前休息期间'
  }
  
  return ''
}

// 获取选项按钮类型
const getOptionButtonType = (optionType, priority = 'medium') => {
  if (priority === 'high') {
    const highPriorityMap = {
      'new_rest_start': 'success',
      'new_rest_end': 'primary',
      'end_current_rest': 'warning'
    }
    return highPriorityMap[optionType] || 'primary'
  } else if (priority === 'low') {
    return 'info'
  }
  
  const typeMap = {
    'modify_start': 'warning',
    'modify_end': 'warning', 
    'new_rest_start': 'success',
    'new_rest_end': 'info',
    'end_current_rest': 'danger'
  }
  return typeMap[optionType] || 'primary'
}

// 处理复杂操作
const handleComplexAction = async (option) => {
  try {
    switch (option.type) {
      case 'modify_start':
        await handleModifyStart(option)
        break
      case 'modify_end':
        await handleModifyEnd(option)
        break
      case 'new_rest_start':
        await handleNewRestStart(option)
        break
      case 'new_rest_end':
        await handleNewRestEnd(option)
        break
      case 'end_current_rest':
        await handleEndCurrentRest(option)
        break
      default:
        ElMessage.warning('未知操作类型')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败：' + error.message)
    }
  }
}

// 修改休息开始日期
const handleModifyStart = async (option) => {
  await ElMessageBox.confirm(
    `确定要${option.description}吗？`,
    '修改休息开始日期',
    { type: 'warning' }
  )
  
  const updatedRecord = {
    ...option.target,
    startDate: option.newDate
  }
  
  // 验证修改后的记录是否与其他记录冲突
  const validation = validateRecordUpdate(updatedRecord)
  if (!validation.valid) {
    throw new Error(validation.message)
  }
  
  await store.updateRestRecord(option.target.id, updatedRecord)
  ElMessage.success('修改成功')
  showDayDialog.value = false
  
  // 刷新统计数据
  await updateStatistics()
  generateCalendar()
}

// 修改休息结束日期
const handleModifyEnd = async (option) => {
  await ElMessageBox.confirm(
    `确定要${option.description}吗？`,
    '修改休息结束日期',
    { type: 'warning' }
  )
  
  const updatedRecord = {
    ...option.target,
    endDate: option.newDate
  }
  
  // 验证修改后的记录是否与其他记录冲突
  const validation = validateRecordUpdate(updatedRecord)
  if (!validation.valid) {
    throw new Error(validation.message)
  }
  
  await store.updateRestRecord(option.target.id, updatedRecord)
  ElMessage.success('修改成功')
  showDayDialog.value = false
  
  // 刷新统计数据
  await updateStatistics()
  generateCalendar()
}

// 新增休息开始
const handleNewRestStart = async (option) => {
  try {
    const today = new Date()
    const todayStr = today.getFullYear() + '-' + 
                    String(today.getMonth() + 1).padStart(2, '0') + '-' + 
                    String(today.getDate()).padStart(2, '0')
    
    // 检查是否需要强制选择结束日期
    const dateRange = analyzeAvailableDateRange(option.startDate, 'start')
    const isFuture = option.startDate > todayStr
    const isToday = option.startDate === todayStr
    
    // 如果是历史日期且没有有效的日期范围，阻止操作
    if (!dateRange.hasValidRange && option.startDate < todayStr) {
      ElMessage.error('无法在此日期开始休息：与现有休息记录间隔不足，无法设置有效的结束日期')
      return
    }
    
    // 如果是历史日期且后面有休息记录，强制选择结束日期
    if (dateRange.hasValidRange && dateRange.maxDate < todayStr) {
      simpleDatePickerConfig.value = {
        title: '选择休息结束日期',
        infoText: `休息开始：${option.startDate}`,
        placeholder: '请选择结束日期',
        dateRange: dateRange,
        startDate: option.startDate,
        referenceDate: option.startDate
      }
      showSimpleDatePicker.value = true
      showDayDialog.value = false
      return
    }
    
    // 否则直接创建休息记录
    const record = {
      startDate: option.startDate,
      endDate: null, // 默认没有结束日期
      description: ''
    }
    
    // 验证记录的有效性
    const validation = validateRecordUpdate(record)
    if (!validation.valid) {
      ElMessage.error(validation.message)
      return
    }
    
    await store.addRestRecord(record)
    
    // 如果是未来日期，设置未来选择标记
    if (isFuture) {
      store.futureSelectedDate = option.startDate
    }
    
    ElMessage.success(isFuture ? '未来休息已预设' : '休息开始记录添加成功')
    showDayDialog.value = false
    
    // 刷新统计数据
    await updateStatistics()
    generateCalendar()
  } catch (error) {
    ElMessage.error('添加失败：' + error.message)
  }
}

// 新增休息结束
const handleNewRestEnd = async (option) => {
  // 分析可用的开始日期范围
  const dateRange = analyzeAvailableDateRange(option.endDate, 'end')
  
  if (!dateRange.hasValidRange) {
    ElMessage.error('无法在此日期结束休息：与现有休息记录间隔不足，无法设置有效的开始日期')
    return
  }
  
  // 打开休息记录对话框，预设结束日期和日期范围
  editingRecord.value = null
  selectedRestStartDate.value = null // 确保清空开始日期预设
  selectedRestEndDate.value = option.endDate
  selectedDateRange.value = dateRange
  showRestDialog.value = true
  showDayDialog.value = false
}

// 结束当前休息
const handleEndCurrentRest = async (option) => {
  await ElMessageBox.confirm(
    `确定要${option.description}吗？`,
    '结束休息',
    { type: 'warning' }
  )
  
  const updatedRecord = {
    ...option.target,
    endDate: option.newDate
  }
  
  await store.updateRestRecord(option.target.id, updatedRecord)
  
  // 如果是未来日期，设置未来选择标记
  const today = new Date().toISOString().split('T')[0]
  if (option.newDate > today) {
    store.futureSelectedDate = option.newDate
  }
  
  ElMessage.success('休息结束')
  showDayDialog.value = false
  
  // 刷新统计数据
  await updateStatistics()
  generateCalendar()
}

// 验证记录更新是否合法
const validateRecordUpdate = (record) => {
  const today = new Date()
  const todayStr = today.getFullYear() + '-' + 
                  String(today.getMonth() + 1).padStart(2, '0') + '-' + 
                  String(today.getDate()).padStart(2, '0')
  
  // 检查与其他记录的冲突
  const conflict = store.checkDateConflict(record.startDate, record.endDate, record.id)
  if (conflict) {
    return { valid: false, message: `与现有休息记录${conflict.startDate}-${conflict.endDate || '进行中'}存在时间冲突` }
  }
  
  // 如果是今天或未来开始的进行中休息记录，只检查与历史记录的间隔
  if (!record.endDate && record.startDate >= todayStr) {
    const sortedRecords = store.getSortedRestRecords().filter(r => r.id !== record.id)
    
    // 只检查与之前记录的间隔
    for (const otherRecord of sortedRecords) {
      const otherEnd = otherRecord.endDate || otherRecord.startDate
      if (otherEnd < record.startDate) {
        if (!store.validateDateInterval(otherEnd, record.startDate)) {
          return { 
            valid: false, 
            message: `与休息记录${otherRecord.startDate}-${otherRecord.endDate || '进行中'}之间必须至少间隔1天工作时间` 
          }
        }
      }
    }
    return { valid: true }
  }
  
  // 对于有结束日期的记录或历史记录，进行完整的间隔检查
  const sortedRecords = store.getSortedRestRecords().filter(r => r.id !== record.id)
  
  for (const otherRecord of sortedRecords) {
    const recordStart = new Date(record.startDate)
    const recordEnd = record.endDate ? new Date(record.endDate) : new Date()
    const otherStart = new Date(otherRecord.startDate)
    const otherEnd = otherRecord.endDate ? new Date(otherRecord.endDate) : new Date()
    
    // 检查间隔
    if (recordEnd < otherStart) {
      // 当前记录在其他记录之前
      if (!store.validateDateInterval(record.endDate || record.startDate, otherRecord.startDate)) {
        return { 
          valid: false, 
          message: `与休息记录${otherRecord.startDate}-${otherRecord.endDate || '进行中'}之间必须至少间隔1天工作时间` 
        }
      }
    } else if (recordStart > otherEnd) {
      // 当前记录在其他记录之后
      if (!store.validateDateInterval(otherRecord.endDate || otherRecord.startDate, record.startDate)) {
        return { 
          valid: false, 
          message: `与休息记录${otherRecord.startDate}-${otherRecord.endDate || '进行中'}之间必须至少间隔1天工作时间` 
        }
      }
    }
  }
  
  return { valid: true }
}

// 分析可用的日期范围
const analyzeAvailableDateRange = (targetDate, type) => {
  const sortedRecords = store.getSortedRestRecords()
  const today = new Date()
  const todayStr = today.getFullYear() + '-' + 
                  String(today.getMonth() + 1).padStart(2, '0') + '-' + 
                  String(today.getDate()).padStart(2, '0')
  
  let minDate = store.user.tripStartDate
  let maxDate = todayStr
  
  // 找到目标日期前后的休息记录
  let prevRecord = null
  let nextRecord = null
  
  for (let i = 0; i < sortedRecords.length; i++) {
    const record = sortedRecords[i]
    const recordStart = record.startDate
    const recordEnd = record.endDate || todayStr
    
    if (targetDate > recordEnd) {
      prevRecord = record
    } else if (targetDate < recordStart) {
      nextRecord = record
      break
    }
  }
  
  if (type === 'end') {
    // 如果是设置结束日期，需要找到合适的开始日期范围
    if (prevRecord) {
      // 开始日期必须在上一个休息记录结束后至少2天（保证至少1天工作间隔）
      const prevEndDate = new Date(prevRecord.endDate || prevRecord.startDate)
      prevEndDate.setDate(prevEndDate.getDate() + 2) // 至少间隔1天工作时间
      minDate = formatDate(prevEndDate)
    }
    
    // 开始日期最晚可以等于结束日期（当天开始当天结束）
    maxDate = targetDate
  } else if (type === 'start') {
    // 如果是设置开始日期，需要找到合适的结束日期范围
    // 结束日期最早可以等于开始日期（当天开始当天结束）
    minDate = targetDate
    
    if (nextRecord) {
      // 结束日期必须在下一个休息记录开始前至少2天（保证至少1天工作间隔）
      const nextStartDate = new Date(nextRecord.startDate)
      nextStartDate.setDate(nextStartDate.getDate() - 2) // 至少间隔1天工作时间
      maxDate = formatDate(nextStartDate)
    }
  }
  
  return {
    hasValidRange: minDate <= maxDate,
    minDate,
    maxDate,
    type,
    targetDate,
    message: type === 'end' 
      ? `请选择${minDate}到${maxDate}之间的开始日期` 
      : `请选择${minDate}到${maxDate}之间的结束日期`
  }
}

const editRecord = (record) => {
  editingRecord.value = record
  showRestDialog.value = true
}

const deleteRecord = async (record) => {
  try {
    await ElMessageBox.confirm('确定要删除这条休息记录吗？', '确认删除', {
      type: 'warning'
    })
    
    await store.deleteRestRecord(record.id)
    ElMessage.success('删除成功')
    
    // 刷新统计数据
    await updateStatistics()
    generateCalendar()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const saveRestRecord = async (record) => {
  try {
    // 验证新记录或更新记录的有效性
    const recordToValidate = editingRecord.value ? { ...record, id: editingRecord.value.id } : record
    const validation = validateRecordUpdate(recordToValidate)
    
    if (!validation.valid) {
      ElMessage.error(validation.message)
      return
    }
    
    if (editingRecord.value) {
      await store.updateRestRecord(editingRecord.value.id, record)
      ElMessage.success('更新成功')
    } else {
      await store.addRestRecord(record)
      ElMessage.success('添加成功')
    }
    
    showRestDialog.value = false
    editingRecord.value = null
    selectedRestStartDate.value = null
    selectedRestEndDate.value = null
    selectedDateRange.value = null
    
    // 刷新统计数据
    await updateStatistics()
    generateCalendar()
  } catch (error) {
    ElMessage.error('保存失败：' + error.message)
  }
}

const updateStatistics = async () => {
  // 如果用户未设置出差开始日期，不执行统计更新
  if (!store.user.tripStartDate) {
    return
  }
  
  try {
    const params = { includeTravel: includeTravel.value }
    
    // 如果用户选择了自定义日期范围
    if (statisticsDateRange.value && statisticsDateRange.value.length === 2) {
      params.startDate = statisticsDateRange.value[0]
      params.endDate = statisticsDateRange.value[1]
    }
    
    await store.getStatistics(params)
  } catch (error) {
    console.warn('更新统计失败:', error)
    ElMessage.error('更新统计失败')
  }
}

// 禁用统计日期选择器中的日期
const disableStatisticsDate = (date) => {
  const today = new Date()
  today.setHours(23, 59, 59, 999)
  
  // 不能选择未来日期
  if (date > today) return true
  
  // 不能早于出差开始日期
  if (store.user.tripStartDate) {
    const tripStartDate = new Date(store.user.tripStartDate)
    tripStartDate.setHours(0, 0, 0, 0)
    if (date < tripStartDate) return true
  }
  
  return false
}

// 处理统计日期范围变化
const onStatisticsDateRangeChange = (dateRange) => {
  if (dateRange && dateRange.length === 2) {
    updateStatistics()
  } else if (!dateRange) {
    // 清空时重置为默认范围
    resetStatisticsDateRange()
  }
}

// 初始化统计日期范围
const initializeStatisticsDateRange = () => {
  if (store.user.tripStartDate) {
    const today = new Date()
    const todayStr = today.getFullYear() + '-' + 
                    String(today.getMonth() + 1).padStart(2, '0') + '-' + 
                    String(today.getDate()).padStart(2, '0')
    
    statisticsDateRange.value = [store.user.tripStartDate, todayStr]
  }
}

// 重置统计日期范围为默认
const resetStatisticsDateRange = () => {
  initializeStatisticsDateRange()
  updateStatistics()
}

const prevMonth = async () => {
  if (currentMonth.value === 1) {
    currentMonth.value = 12
    currentYear.value--
  } else {
    currentMonth.value--
  }
  
  const result = await store.getHolidayData(currentYear.value)
  // 如果该年份暂无节假日数据，显示提示
  if (result && result.hasData === false) {
    ElMessage.info(`${result.emptyYear || currentYear.value}年暂无节假日数据`)
  }
  generateCalendar()
}

const nextMonth = async () => {
  if (currentMonth.value === 12) {
    currentMonth.value = 1
    currentYear.value++
  } else {
    currentMonth.value++
  }
  
  const result = await store.getHolidayData(currentYear.value)
  // 如果该年份暂无节假日数据，显示提示
  if (result && result.hasData === false) {
    ElMessage.info(`${result.emptyYear || currentYear.value}年暂无节假日数据`)
  }
  generateCalendar()
}

const goToday = () => {
  const today = new Date()
  currentYear.value = today.getFullYear()
  currentMonth.value = today.getMonth() + 1
  generateCalendar()
}

// 处理简化日期选择器确认
const handleSimpleDateConfirm = async (endDate) => {
  try {
    const config = simpleDatePickerConfig.value
    const record = {
      startDate: config.startDate,
      endDate: endDate,
      description: ''
    }
    
    // 验证记录的有效性
    const validation = validateRecordUpdate(record)
    if (!validation.valid) {
      ElMessage.error(validation.message)
      return
    }
    
    await store.addRestRecord(record)
    ElMessage.success('休息记录添加成功')
    
    // 刷新统计数据
    await updateStatistics()
    generateCalendar()
  } catch (error) {
    ElMessage.error('添加失败：' + error.message)
  }
}

const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '确认退出', {
      type: 'warning'
    })
    
    await store.logout()
    ElMessage.success('退出登录成功')
    router.push('/login')
  } catch (error) {
    // 用户取消或登出失败
    if (error !== 'cancel') {
      ElMessage.error('退出登录失败，但已清除本地状态')
      router.push('/login')
    }
  }
}
</script>

<style scoped>
.dashboard {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.app-header {
  background: white;
  padding: 16px 24px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.app-title {
  font-size: 20px;
  color: #333;
  margin: 0;
}

.trip-info {
  font-size: 14px;
  color: #666;
  margin-top: 4px;
}

.trip-start {
  color: #67c23a;
}

.no-trip {
  color: #f56c6c;
}

.app-main {
  display: flex;
  gap: 20px;
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.calendar-section {
  flex: 1;
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.calendar-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 20px;
}

.month-title {
  font-size: 18px;
  color: #333;
  margin: 0;
}

.weekday-header {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 1px;
  margin-bottom: 1px;
}

.weekday-cell {
  background-color: #f5f7fa;
  padding: 12px 8px;
  text-align: center;
  font-weight: 500;
  color: #606266;
  font-size: 14px;
}

.calendar-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 1px;
  background-color: #e0e0e0;
}

.calendar-day {
  background-color: white;
  min-height: 120px;
  padding: 8px;
  cursor: pointer;
  position: relative;
  transition: all 0.2s ease;
}

.calendar-day:hover {
  border: 2px solid #409eff;
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.2);
}

/* 基础日期类型底色 */
.date-type-0 { background-color: #f0f8ff; } /* 工作日-浅蓝 */
.date-type-1 { background-color: #fff8dc; } /* 周末-浅黄 */
.date-type-2 { background-color: #ffe4e1; } /* 节假日-浅红 */
.date-type-3 { background-color: #f0fff0; } /* 调休-浅绿 */

/* 今天的特殊样式 */
.is-today {
  background-color: #e6f7ff !important; /* 今天-浅青色 */
  border: 2px solid #1890ff !important;
  box-shadow: 0 0 8px rgba(24, 144, 255, 0.3);
}

/* 特殊状态 */
.empty-day {
  background-color: transparent;
  cursor: default;
  pointer-events: none;
}

.before-trip { 
  background-color: #ffffff; 
  color: #c0c4cc;
  cursor: not-allowed;
}

.trip-start {
  border: 2px solid #67c23a !important;
}

.rest-period {
  border: 2px solid #e6a23c !important;
}

.is-today .today-marker {
  position: absolute;
  top: 2px;
  right: 2px;
  width: 8px;
  height: 8px;
  background-color: #f56c6c;
  border-radius: 50%;
}

.day-number {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 4px;
}

.day-labels {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  margin-bottom: 4px;
}

.weekday-label {
  color: #909399;
}

.type-label {
  color: #606266;
}

.holiday-name {
  font-size: 11px;
  color: #f56c6c;
  font-weight: bold;
  margin-bottom: 2px;
}

.user-status {
  position: absolute;
  bottom: 4px;
  right: 4px;
}

.info-panel {
  width: 320px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.stats-card, .records-card {
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.card-header {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
}

.header-left {
  display: flex;
  flex-direction: column;
  gap: 8px;
  width: 100%;
}

.title-row {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-title {
  font-weight: 600;
  font-size: 16px;
}

.travel-checkbox {
  font-size: 12px;
}

.travel-checkbox :deep(.el-checkbox__label) {
  font-size: 12px;
  color: #666;
}

.date-range-selector {
  display: flex;
  align-items: center;
}

.period-info {
  font-size: 12px;
  color: #666;
  font-weight: normal;
}

.stats-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stat-label {
  color: #666;
}

.stat-value {
  font-weight: bold;
  font-size: 16px;
}

.work-days { color: #409eff; }
.rest-days { color: #67c23a; }
.should-rest { color: #e6a23c; }
.owed-rest { color: #f56c6c; }
.owed-rest.negative { color: #67c23a; }

.records-content {
  max-height: 400px;
  overflow-y: auto;
}

.record-item {
  padding: 12px 0;
  border-bottom: 1px solid #eee;
}

.record-item:last-child {
  border-bottom: none;
}

.record-dates {
  font-weight: 500;
  margin-bottom: 4px;
}

.record-description {
  color: #666;
  font-size: 14px;
  margin-bottom: 8px;
}

.record-actions {
  display: flex;
  gap: 8px;
}

.day-info {
  margin-bottom: 20px;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.selected-date {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}

.date-type {
  font-size: 14px;
  color: #666;
  margin-bottom: 4px;
}

.holiday-info {
  font-size: 14px;
  color: #f56c6c;
  font-weight: bold;
  margin: 0;
}

.day-actions {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.action-tip {
  font-size: 13px;
  color: #909399;
  text-align: center;
  margin: 8px 0 0 0;
  line-height: 1.4;
}

.complex-options {
  max-height: 400px;
  overflow-y: auto;
}

.options-title {
  font-size: 14px;
  font-weight: bold;
  color: #333;
  margin-bottom: 16px;
  text-align: center;
}

.option-item {
  margin-bottom: 16px;
}

.option-description {
  font-size: 12px;
  color: #666;
  text-align: center;
  margin: 4px 0 0 0;
  line-height: 1.3;
}

.no-options {
  text-align: center;
  padding: 20px;
  color: #909399;
}

.no-options p {
  margin: 8px 0;
}

.no-options-tip {
  font-size: 12px;
  color: #c0c4cc;
}

.high-priority {
  margin-bottom: 16px;
}

.low-priority-section {
  margin-top: 12px;
  border-top: 1px solid #ebeef5;
  padding-top: 12px;
}

.low-priority-options {
  margin-top: 8px;
}

.option-item.low-priority {
  margin-bottom: 8px;
}

.option-description.low {
  font-size: 11px;
  color: #909399;
  opacity: 0.8;
}
</style>
